<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :span="24" class="card-box">
        <el-card>
          <div>流程总览</div>
          <div class="flex-container row">
            <div class="flex-item" @click="getRecordList(1)">
              <div class="flex-item-img">
                <img class="flex-item-img right" src="@/assets/images/file-cabinet.png" alt="404">
              </div>
            </div>
            <div class="flex-item" @click="getRecordList(1)">
              <div class="flex-item-text">
                <div style="height: 25px;line-height: 25px;">待办流程</div>
                <div style="height: 25px;line-height: 25px;text-align: center;">{{ todoNum }}</div>
              </div>
            </div>
            <div class="flex-item" style="    margin-left: 30px;" @click="getRecordList(2)">
              <div class="flex-item-img">
                <img class="flex-item-img right" src="@/assets/images/data-sheet.jpg" alt="404">
              </div>
            </div>
            <div class="flex-item" @click="getRecordList(2)">
              <div class="flex-item-text">
                <div style="height: 25px;line-height: 25px;">已办流程</div>
                <div style="height: 25px;line-height: 25px;text-align: center;">{{ doneNum }}</div>
              </div>
            </div>
            <div class="flex-item" style="margin-left: 30px;" @click="toApplyTask">
              <div class="flex-item-img">
                <img class="flex-item-img right" src="@/assets/images/new_apply.jpg" alt="404">
              </div>
            </div>
            <div class="flex-item" @click="toApplyTask">
              <div class="flex-item-text">
                <div style="height: 25px;line-height: 25px;">新建流程</div>
              </div>
            </div>
            <div class="flex-item" style="margin-left: 30px;" @click="toExportTask" v-if="userLevel > 2">
              <div class="flex-item-img">
                <img class="flex-item-img right" src="@/assets/images/export.svg" alt="404">
              </div>
            </div>
            <div class="flex-item" @click="toExportTask" v-if="userLevel > 2">
              <div class="flex-item-text">
                <div style="height: 25px;line-height: 25px;">导出</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" class="card-box">
        <el-card style="height: 700px;">
          <el-table v-loading="loading" :data="flowList"  border >
            <el-table-column label="序号" type="index" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="流水号" align="center" prop="serialNumber"/>
            <el-table-column label="标题" align="center" prop="recordTitle" :show-overflow-tooltip="true"/>
            <el-table-column label="问题列表日期" align="center" prop="applicantTime"/>
            <el-table-column label="负责部门" align="center" prop="approverUserName"/>
            <el-table-column label="描述" align="center" prop="problemRemark" :show-overflow-tooltip="true"/>
            <el-table-column label="负责人" align="center" prop="personLiableName"/>
            <el-table-column label="状态" align="center" prop="checkStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.meet_execution_status" :value="scope.row.checkStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="层级" align="center" prop="taskStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.user_level_options" :value="scope.row.taskStatus"/>
              </template>
            </el-table-column>>
            <el-table-column label="紧急度" align="center" prop="urgency" width="60">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.meet_urgency"
                          :value="scope.row.urgency"
                          :style="{ color: scope.row.urgency === '高' ? 'red' : '' }"
                          :class="{ 'font-bold': scope.row.urgency === '高' }"
                />
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['conference:flow:edit']"
                >查看待办
                </el-button>
                <el-button v-if="loginUser == scope.row.applicantUserId "
                           size="mini"
                           type="text"
                           icon="el-icon-edit"
                           @click="handleCancel(scope.row)"
                           v-hasPermi="['conference:flow:edit']"
                >撤回</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <div style="    width: 100%;padding-bottom: 10px;padding-left: 16px;">
        <el-button type="success" @click="prev" :loading="prevLoading">上一条</el-button>
        <el-button type="success" @click="next" :loading="nextLoading">下一条</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">关 闭</el-button>
        <span style="font-size: 20px;font-weight: bold;padding-left: 50px;">{{form.recordTitle}}_{{form.userName}}_{{form.serialNumber}}</span>
<!--        <span style="font-size: 20px;font-weight: bold;padding-left: 30px; color: #ed5565"  v-if="form.taskStatus < 4 && form.checkStatus == '1'"> 处理倒计时：{{countdown}}</span>-->
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
        <el-row>
          <el-col :span="8" class="card-box">
            <el-card>
              <div slot="header"><span><i class="el-icon-link"></i> 发起信息</span></div>
              <el-form-item label="申请人部门" prop="applicantDetpCode">
                <el-select v-model="form.applicantDetpCode" :disabled="isDisabled" >
                  <el-option
                    v-for="item in deptOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="问题层级" prop="taskStatus">
                <el-select v-model="form.taskStatus" :disabled="isDisabled" >
                  <el-option
                    v-for="dict in dict.type.user_level_options"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="层级审批人" prop="approverUserId">
                <el-select v-model="form.approverUserId"
                           filterable   :disabled="isDisabled" >
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="申请时间" prop="applicantTime">
                <el-date-picker clearable
                                v-model="form.applicantTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"  :readonly="isReadOnly"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="计划交货日期" prop="plannedDeliveryTime" v-if="form.recordType == 1">
                <el-date-picker clearable
                                v-model="form.plannedDeliveryTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" :readonly="isReadOnly"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="产品大类" prop="productCategory" v-if="form.recordType == 1">
                <el-select v-model="form.productCategory"  :readonly="isReadOnly" >
                  <el-option
                    v-for="dict in dict.type.product_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="订单号" prop="orderNo" v-if="form.recordType == 1">
                <el-input v-model="form.orderNo"  :readonly="isReadOnly" />
              </el-form-item>
              <el-form-item label="生产批号" prop="produceBathNo" v-if="form.recordType == 1">
                <el-input v-model="form.produceBathNo"  :readonly="isReadOnly" />
              </el-form-item>
              <el-form-item label="物料号" prop="materialNo" v-if="form.recordType == 1">
                <el-input v-model="form.materialNo"  :readonly="isReadOnly" />
              </el-form-item>
              <el-form-item label="问题描述" prop="problemRemark">
                <el-input v-model="form.problemRemark" type="textarea" :rows="6" :readonly="isReadOnly" />
              </el-form-item>
              <el-form-item label="附件上传" prop="fileUrl">
                <file-upload v-model="form.fileUrl"/>
              </el-form-item>
            </el-card>
          </el-col>

          <el-col :span="8" class="card-box">
            <el-card>
              <div slot="header"><span><i class="el-icon-user"></i> 受理信息</span></div>
              <el-form-item label="影响KPI" prop="kpiName">
                <el-select v-model="form.kpiName"  placeholder="请选择影响KPI">
                  <el-option
                    v-for="dict in dict.type.impact_kpi"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="负责人" prop="personLiableName">
                <el-input v-model="form.personLiableName"  placeholder="请输入负责人"/>
              </el-form-item>
              <el-form-item label="问题类型" prop="problemType">
                <el-select v-model="form.problemType"  placeholder="请选择问题类型">
                  <el-option
                    v-for="dict in dict.type.problem_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="计划完成日期" prop="planFinishTime">
                <el-date-picker clearable
                                v-model="form.planFinishTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选计划完成日期"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="实际完成日期" prop="actualFinishTime">
                <el-date-picker clearable
                                v-model="form.actualFinishTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择实际完成日期"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="行动计划" prop="meetAction">
                <el-input v-model="form.meetAction" type="textarea" :rows="6" placeholder="请输入行动计划"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"  size="mini" @click="handleUpdateRecord">更新</el-button>
              </el-form-item>

            </el-card>
          </el-col>

          <el-col :span="8" class="card-box">
            <el-card>
              <div slot="header"><span><i class="el-icon-question"></i> 问题状态</span></div>
              <el-form-item label="状态" prop="checkStatus">
                <el-select v-model="form.checkStatus"  >
                  <el-option label="开始" value="1" />
                  <el-option v-if="form.checkStatus !=4 && form.checkStatus !=3" label="结束" value="2" />
                  <el-option v-if="form.checkStatus !=1 && form.checkStatus !=2" label="驳回" value="3" />
                  <el-option v-if="form.checkStatus !=1 && form.checkStatus !=2" label="关闭" value="4" />
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.checkStatus == 1" label="处理" prop="operationStatus">
                <el-select v-model="form.operationStatus">
                  <el-option label="升级" value="1" />
                  <el-option label="委托" value="3" />
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.operationStatus == 3" label="委托部门" prop="commissionUserId">
                <el-select v-model="form.commissionUserId"  ref='selectPerson' placeholder="请选择委托部门"
                           filterable>
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最近更新" prop="applicantTime">
                <el-date-picker clearable
                                v-model="form.applicantTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-card>
          </el-col>

          <el-col :span="24" class="card-box">
            <el-card>
              <div slot="header"><span><i class="el-icon-list"></i> 历史行动计划</span></div>
              <div class="el-table el-table--enable-row-hover el-table--medium">
                <table cellspacing="0" style="width: 100%;">
                  <thead>
                  <tr>
                    <th class="el-table__cell is-leaf"><div class="cell">操作人</div></th>
                    <th class="el-table__cell is-leaf"><div class="cell">操作时间</div></th>
                    <th class="el-table__cell is-leaf"><div class="cell">操作状态</div></th>
                    <th class="el-table__cell is-leaf"><div class="cell">流程节点</div></th>
                    <th class="el-table__cell is-leaf"><div class="cell">行动计划</div></th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr :key="index" v-for="(item, index) in form.flowList">
                    <td class="el-table__cell is-leaf"><div class="cell" v-if="item.meetSimName">{{ item.meetSimName }}</div></td>
                    <td class="el-table__cell is-leaf"><div class="cell" v-if="item.meetSimTime">{{ item.meetSimTime }}</div></td>
                    <td class="el-table__cell is-leaf"><div class="cell" v-if="item.meetStatus">
                      <!--{{ item.meetStatus }}-->
                      <template >
                        <dict-tag :options="dict.type.meet_operation_status" :value="item.meetStatus"/>
                      </template>
                    </div></td>
                    <td class="el-table__cell is-leaf"><div class="cell" v-if="item.taskStatus">
                      <!--{{ item.meetStatus }}-->
                      <template >
                        <dict-tag :options="dict.type.user_level_options" :value="item.taskStatus"/>
                      </template>
                    </div></td>
                    <td class="el-table__cell is-leaf"><div class="cell" v-if="item.meetAction">{{ item.meetAction }}</div></td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  closeRecord,
  getFlow,
  getIds,
  getToDoNum,
  listFlow,
  rejectRecord,
  updateFlow,
  updateProblemLevel,updateRecord
} from "@/api/conference/flow";
import {deptTreeSelect, getUserByUserName} from "@/api/system/user";
import moment from "@/utils/moment";

export default {
  name: "Index",
  dicts: ['meet_urgency', 'user_level_options', 'product_category', 'meet_process_status', 'meet_execution_status', 'impact_kpi', 'problem_type', 'meet_operation_status'],
  data() {
    return {
      prevLoading: false,
      nextLoading: false,
      autoUpgradationTime: '',
      countdown: '', // 用于显示倒计时的字符串
      timer: null, // 用于存储定时器的ID
      // 版本号
      version: "3.8.8",
      // 总条数
      total: 0,
      // 遮罩层
      loading: true,
      // 待办表格数据
      flowList: [],
      userLevel:null,
      doneNum: 0,
      todoNum: 0,
      currentIndex: 0,
      loginUser:null,
      recordIds: undefined,
      userList: undefined,
      deptOptions: undefined,
      title: '',
      open: false,
      isDisabled: true,
      isReadOnly: true,
      listType:1,
      // 表单参数
      form: {},
      rules: {
        meetAction: [
          {required: true, message: "请填写行动计划", trigger: "blur"}
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        listType: "1",
        problemStartDate: null,
        problemEndDate: null,
        problemLevel: null,
        taskStatus: null,
        applicantDetpCode: null
      },
    };
  },
  created() {
    this.getList();
    this.getNum()
    this.getDeptTree();
    this.queryUser();
    this.getAllRecordIds()
    this.loginUser  = this.$store.state.user.id
    this.userLevel = this.$store.state.user.userLevel
  },
  methods: {
    goTarget(href) {
      window.open(href, "_blank");
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data[0].children;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    async prev() {
      if (this.currentIndex - 1 < 0) {
        this.$modal.msgError("已是第一条数据");
        return;
      }
      this.prevLoading = true
      this.reset();
      const id = this.recordIds[this.currentIndex - 1]
      await getFlow(id).then(response => {
        this.form = response.data;
        // this.autoUpgradationTime = moment(this.form.autoUpgradationTime)
        // 初始化倒计时
        //this.startCountdown();
        this.handleEditStatus(response.data.meetStatus)
      });
      this.currentIndex = this.currentIndex - 1
      this.prevLoading = false
    },
    async next() {
      if (this.currentIndex + 1 >= this.recordIds.length) {
        this.$modal.msgError("已是最后一条数据");
        return;
      }
      this.nextLoading = true
      this.reset();
      const id = this.recordIds[this.currentIndex + 1]
      await getFlow(id).then(response => {
        this.form = response.data;
        //this.autoUpgradationTime = moment(this.form.autoUpgradationTime)
        // 初始化倒计时
        //this.startCountdown();
        this.handleEditStatus(response.data.meetStatus)
      });
      this.currentIndex = this.currentIndex + 1
      this.nextLoading = false
    },
    closeMeetRecord() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            closeRecord(this.form).then(response => {
              this.$modal.msgSuccess("关闭成功");
            });
          } else {
            this.$modal.msgError("系统错误");
          }
        }
      });
    },
    rejectMeetRecord() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            rejectRecord(this.form).then(response => {
              this.$modal.msgSuccess("拒绝成功");
            });
          } else {
            this.$modal.msgError("系统错误");
          }
        }
      });
    },
    handleCancel(row){
      const id = row.id || this.ids
      if (id != null) {
        closeRecord(id).then(response => {
          this.$modal.msgSuccess("撤销成功");
          this.getList();
        });
      } else {
        this.$modal.msgError("系统错误");
      }
    },
    updateMeetRecord() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProblemLevel(this.form).then(response => {
              this.$modal.msgSuccess("升级成功");
              this.getList();
            });
          } else {
            this.$modal.msgError("系统错误");
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFlow(this.form).then(response => {
              this.$modal.msgSuccess("提交成功");
              this.getList();
              this.getNum()
              this.getAllRecordIds()
            });
          }
        }
      });
    },
    getAllRecordIds() {
      getIds(this.queryParams).then(response => {
        this.recordIds = response.data;
      });
    },
    queryUser() {
      const dataReq = {
        userName: ''
      }
      getUserByUserName(dataReq).then(response => {
        this.userList = response.data;
      });
    },
    getRecordList(listType){
      if (listType) {
        this.queryParams.listType = listType
      }
      this.getList()
    },
    getList() {
      this.loading = true;
      listFlow(this.queryParams).then(response => {
        this.flowList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getNum() {
      getToDoNum().then(response => {
        this.doneNum = response.data.doneNum;
        this.todoNum = response.data.toDoNum;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        meetRecordId: null,
        meetSimName: null,
        meetSimCode: null,
        meetSimTime: null,
        meetStatus: null
      };
      this.resetForm("form");
    },
    handleUpdateRecord(){
      console.log("update")
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("更新成功");
              this.getList();
              getFlow(this.recordIds[this.currentIndex]).then(response => {
                this.form = response.data;
                this.handleEditStatus(response.data.meetStatus)
              });
            });
          }
        }
      });
    },
    handleEditStatus(status) {
      if (status == 3) {
        this.isDisabled = false;
        this.isReadOnly = false;
      } else {
        this.isDisabled = true;
        this.isReadOnly = true;
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      await getFlow(id).then(response => {
        this.form = response.data;
       // this.autoUpgradationTime = moment(this.form.autoUpgradationTime)
        this.open = true;
        // 初始化倒计时
        //this.startCountdown();
        this.handleEditStatus(response.data.meetStatus)
        this.title = "修改待办";
      });
      let selectIndex = 0
      this.recordIds.forEach(function (item, index, recordIds) {
        if (item == id) {
          selectIndex = index
          return
        }
      })
      this.currentIndex = selectIndex
    },
    // 初始化并启动倒计时
    startCountdown() {
      if (!this.autoUpgradationTime) return;

      // 计算24小时后的时间点
      const targetTime = this.autoUpgradationTime.clone().add(24, 'hours');

      // 立即更新一次倒计时，然后设置定时器每秒更新
      this.updateCountdown(targetTime);
      this.timer = setInterval(() => this.updateCountdown(targetTime), 1000);
    },
    updateCountdown(targetTime) {
      const now = moment();

      // 计算剩余时间
      const diff = targetTime.diff(now, 'milliseconds');

      // 如果时间差小于0，则停止倒计时
      if (diff < 0) {
        this.countdown = '00:00:00'; // 倒计时结束
        clearInterval(this.timer);
        return;
      }

      // 将毫秒转换为小时、分钟和秒
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((diff % (1000 * 60)) / 1000);

      // 格式化并更新倒计时
      this.countdown = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;

      console.log('1112321132312:   ',this.countdown)
    },
    // 组件销毁时清除定时器
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer);
      }
    },

    toFlowList() {
      this.$router.push("/meet/flow");
    },
    toApplyTask() {
      this.$router.push("/meet/applyTask");
    },
    toExportTask() {
      this.download('conference/applyTask/export', {
        ...this.queryParams
      }, `applyTask_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
.flex-container {
  display: flex;
  flex-wrap: wrap; /* 允许项目换行 */
  padding: 10px;
  justify-content: flex-start;
}

.flex-container.row {
  flex-direction: row;
}

.flex-item {
  width: 50px;
  height: 50px;
  margin: 5px;
  line-height: 50px;
}

.flex-item-img {
  width: 50px;
  height: 50px;
  line-height: 50px;
}

.flex-item-text {
  display: inline-block;
  width: 54px;
  height: 50px;
  line-height: 50px;
}

.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.el-select .el-input.is-disabled .el-input__inner {
  background-color: white !important;
  color: black !important;
}

</style>

